package edu.sjtu.grid.workflow;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.text.DecimalFormat;

public class Util {
	
	public static void main(String args[])
	{
		System.out.println(Util.unitFloor((double)5.55, (double)0.1));
		System.out.println(Util.unitCeil((double)5.55, (double)0.1));
	}
	
	public static boolean isEqualOrSmall(double a, double b)
	{
		return isEqual(a, b) || isSmall(a, b);
	}
	
	public static boolean isEqualOrBig(double a, double b)
	{
		return isEqual(a, b) || isBig(a, b);
	}

	
	public static boolean isEqual(double a, double b)
	{
		return Math.abs(a - b) < 0.0000000001;
	}
	
	public static boolean isSmall(double a, double b)
	{
		if(isEqual(a, b))
			return false;
		else
			return a < b;
	}
	
	public static boolean isBig(double a, double b)
	{
		if(isEqual(a, b))
			return false;
		else
			return a > b;
	}
	
	public static double unitFloor(double data, double unit)
	{
		int n = (int)Math.floor(data / unit);
		if(isSmall(unit * (n + 1), data))
			return unit * (n + 1);
		else
			return unit * n;
	}
	
	public static double unitCeil(double data, double unit)
	{
		int n = (int)Math.ceil(data / unit);
		if(isBig(unit * (n-1), data))
			return unit * (n-1);
		else
			return unit * n;
	}

	public static String formatOutputString(String s, int tabNumber)
	{
		String t = s;
		for(int i=s.length(); i<8*tabNumber; i++)
			t += " ";
		return t;
	}
	
	public static String formatOutputDouble(Double d)
	{
		if(d == null)
			return "null";
		return Util.formatOutputDouble(d, "0.###");
	}
	
	public static String formatOutputDouble(Double d, int tabNumber)
	{
		return Util.formatOutputString(Util.formatOutputDouble(d), tabNumber);
	}
	
	public static String formatOutputDouble(Double d, String form, int tabNumber)
	{
		return Util.formatOutputString(Util.formatOutputDouble(d, form), tabNumber);
	}
	
	public static String formatOutputDouble(Double d, String form)
	{
		if(d == null)
			return "null";
		DecimalFormat decim = new DecimalFormat(form);
		return decim.format(d);
	}
	
	public static void saveToNewFile(String file, String text)
	{
		try{
			File f = new File(file);
			File dir = new File(f.getParent());
			if(!dir.exists())
				dir.mkdirs();
			f.createNewFile();
			FileWriter fstream = new FileWriter(f);
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(text);
			out.close();
		}catch (Exception e){
			System.err.println("Error: " + e.getMessage());
		}
	}
}
